#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define RESULT_FILE "resultat.txt"
double unif01(){
	return rand()/(double)RAND_MAX;
}

double rexp(double param){
	return -log(unif01())/param;
}

double max(double d1, double d2){
	return d1>d2?d1:d2;
}

void response(int n, double lambda, double* rep){
	int i;
	double mu, tau[n], sigma[n], t1[n], t2[n];
	
	mu=1;
	for(i=0; i<n; i++){
		tau[i]=rexp(lambda);
		sigma[i]=rexp(mu);
	}
	
	t1[0]=0;
	t2[0]=0;
	for(i=1; i<n; i++){
		t1[i]=t1[i-1]+tau[i];
		t2[i]=max(t1[i], t2[i-1])+sigma[i];
	}
	
	for(i=0; i<n; i++){
		rep[i]=t2[i]-t1[i];
	}
}

void traj(int n, double lambda){
	double rep[n];
	int i;
	char* file=RESULT_FILE;
	response(n, lambda, rep);
	FILE* fp=fopen(file, "w");
	for(i=0; i<n; i++) fprintf(fp, "%d\t%lf\n", i, rep[i]);
	fclose(fp);
	printf("n=%d\nlambda=%lf\n", n, lambda);
	printf("Resultat dans le fichier %s\n", file);
}

void help(char* app){
	printf("Usage: %s <n> <lambda>\n", app);
}

int main(int argc, char** argv){
	double lambda;
	char* endptr=(char*)1;
	int n;
	
	srand((unsigned)time(NULL));
	
	if(argc>=3){
		n=strtol(argv[1], &endptr, 0);
		lambda=strtod(argv[2], &endptr);
	}
	else {
		help(argv[0]);
		exit(1);
	}
	traj(n, lambda);
	
	return 0;
}